package com.tanhua.controller;

import com.aliyuncs.exceptions.ClientException;
import com.tanhua.domain.Admin;
import com.tanhua.domain.vo.AdminVo;
import com.tanhua.interceptor.AdminHolder;
import com.tanhua.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping(value = "/system")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping(value = "/users/verification", name = "获取验证码图片")
    public ResponseEntity verification(String uuid, HttpServletResponse response) throws ClientException, IOException {
        return adminService.verification(uuid,response);//uuid由浏览器随机生成
    }

    @PostMapping(value ="/users/login", name = "登录")
    public ResponseEntity login(@RequestBody Map<String,String> map) throws ClientException, IOException {
        String username = map.get("username");  //账号
        String password = map.get("password");  //密码
        String verificationCode = map.get("verificationCode"); //验证码
        String uuid = map.get("uuid"); //redis的验证码key
        return adminService.login(username,password,verificationCode,uuid);
    }

    //携带用户数据到首页
    @PostMapping(value ="/users/profile", name = "用户信息的验证")
    public ResponseEntity profile() throws ClientException, IOException {

        //获取token 去redis中拿到之前存的对象数据
        Admin admin = AdminHolder.getAdmin();
        AdminVo adminVo = new AdminVo();
        adminVo.setId(admin.getId().toString());
        BeanUtils.copyProperties(admin,adminVo);
        return ResponseEntity.ok(adminVo);
    }


    @PostMapping(value ="/users/logout", name = "用户登出")
    public ResponseEntity logout() throws ClientException, IOException {

        // 将redis中的token删除
        adminService.logout();
        return ResponseEntity.ok(null);
    }



}
